#include <stdio.h>
#include <stdlib.h>
#include <SDL.h>
#include <SDL_mixer.h>

#define SAMPLE_RATE 44100
#define TONE_DURATION 100  // 节拍持续时间，单位为毫秒

int main(int argc, char* argv[]) {
    if (argc != 3) {
        printf("Usage: %s <bpm> <accent_every_n_beats>\n", argv[0]);
        return 1;
    }

    int bpm = atoi(argv[1]);
    int accentEveryNBeats = atoi(argv[2]);

    if (bpm <= 0 || accentEveryNBeats <= 0) {
        printf("BPM and accent_every_n_beats must be greater than 0.\n");
        return 1;
    }

    // 初始化SDL和Mix
    if (SDL_Init(SDL_INIT_AUDIO) < 0 || Mix_OpenAudio(SAMPLE_RATE, MIX_DEFAULT_FORMAT, 2, 2048) < 0) {
        fprintf(stderr, "Failed to initialize SDL audio: %s\n", SDL_GetError());
        return 1;
    }

    // 加载声音样本
    Mix_Chunk* tone440 = Mix_LoadWAV("tone440.wav");
    Mix_Chunk* tone880 = Mix_LoadWAV("tone880.wav");

    if (!tone440 || !tone880) {
        fprintf(stderr, "Failed to load sound samples: %s\n", SDL_GetError());
        return 1;
    }

    // 计算节拍间隔时间
    int beatInterval = 60 * 1000 / bpm;

    int finish = 0;
    for (int i = 0; !finish ; i++) {
        if (i % accentEveryNBeats == 0) {
            Mix_PlayChannelTimed(-1, tone880, 0, TONE_DURATION);
        } else {
            Mix_PlayChannelTimed(-1, tone440, 0, TONE_DURATION);
        }

        SDL_Delay(beatInterval);

        SDL_Event e;
        // 检查是否需要退出
        while (SDL_PollEvent(&e)) {
            if (e.type == SDL_QUIT) {
                finish = 1;
                break;
            }
        }
    }

    // 清理资源
    Mix_FreeChunk(tone440);
    Mix_FreeChunk(tone880);
    Mix_CloseAudio();
    SDL_Quit();

    return 0;
}
